package com.cxd.base.util.wtj;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wtj
 * @date 2015年12月1日 下午4:16:20
 * @company CXD
 * @version [Copyright (c) 2015 V001]
 */
public class FUtils {

	/**
	 * form 表单转实体 bean
	 */
	public static <T> T formToBean(Class<T> clazz, HttpServletRequest request)
			throws InstantiationException, IllegalAccessException {
		T bean = (T) clazz.newInstance();
		Field[] fields = clazz.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			String fieldName = fields[i].getName();
			String fieldValue = request.getParameter(fieldName);
			if (fieldValue == null || fieldValue == "") {
				continue;
			}
			fields[i].setAccessible(true);
			BUtils.setBean(bean, fields[i], fieldValue);
		}
		return bean;
	}

	public static String readTxtFile(String filePath) {
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				StringBuffer sb = new StringBuffer();
				String lineTxt = "";
				while ((lineTxt = bufferedReader.readLine()) != null) {
					sb.append(lineTxt);
				}
				read.close();
				return sb.toString();
			} else {
				System.out.println("找不到指定的文件");
				return null;
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return null;
	}
}
